var conn = {};
let that = this;
let isfirst = true;


// console.log(getconfig())
WebIM.config = getconfig();
// WebIM.config = config;
conn = WebIM.conn = new WebIM.default.connection({
    appKey: WebIM.config.appkey,
    isHttpDNS: WebIM.config.isHttpDNS,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    apiUrl: WebIM.config.apiURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    heartBeatWait: WebIM.config.heartBeatWait,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval,
    isStropheLog: WebIM.config.isStropheLog,
    delivery: WebIM.config.delivery
})
conn.listen({
    onOpened: function (message) { //连接成功回调 
        console.log('成功登录')
		console.log(conn.isOpened())
		if(conn.isOpened()){//ture为登录，undifined为未登录；
			if(isfirst){
				webvue.$message({
				  message: '登陆成功',
				  type: 'success'
				});
				// return
				setTimeout(()=>{
					window.location.href ='/Materials/chat'
				},3000)
			}else{
				webvue.getFriends();
				webvue.getGroups()
			}
		}
    },
    onClosed: function (message) { },         //连接关闭回调
    onTextMessage: function (message) {//收到文本消息
        console.log("收到文本消息", message);
		if(message.type == 'groupchat'){
			//群聊
			
		}
		var namearr = [];
		var name;
		var sendID;
		if(message.type == 'chat'){
			sendID = message.from;
			name = message.from;
		}else if(message.type == 'groupchat'){
			sendID = message.to;
			webvue.groupList.forEach((item)=>{
				if(item.groupid ==message.to){
					name = item.name
				}
			})
		}
		webvue.ifallmsgclear()
		if(message.ext.other == 'videocall'){
			console.log('videocallvideocallvideocallvideocall')
			console.log(message.ext.confrId)
			console.log(message.ext.password)
			webvue.videochatting = true;
			var msgData = {
				self:'other',
				type:msgtype().TEXT,
				value:message.data,
				from:message.from,
				to:message.to,
				isvideo:true,
			}
			webvue.confrId = message.ext.confrId;
			webvue.password = message.ext.password;
			console.log(webvue.confrId)
			console.log(webvue.password)
		}else if(message.ext.other == 'websocmes'){
			var msgData = {
				self:'websocmes',
				type:msgtype().TEXT,
				value:message.data,
				from:message.from,
				to:message.to,
				websocmes:true,
			}
			// if(message.data.indexOf('退出视频')){
			// 	webvue.videochatting = false;
			// }
		}else if(message.ext.other == 'issharescream'){
			var msgData = {
				self:'other',
				type:msgtype().TEXT,
				value:message.data,
				from:message.from,
				to:message.to,
				issharescream:true,
			}
			webvue.sharing = true;
			webvue.confrId = message.ext.confrId;
			webvue.password = message.ext.password;
		}else{
			var msgData = {
				self:'main',
				type:msgtype().TEXT,
				value:message.data,
				from:message.from,
				to:message.to,
				videocall:false
			}
		}
        webvue.friendshowList.forEach((item,index)=>{
        	namearr.push(item.name)
        })
		if(namearr.indexOf(name) == -1){
			var obj = {
				  name:message.from,
				  lastmsg:message.data,
				  time:'星期一',
				  noreadnum:1,
				  ishidden:false
			}
			webvue.friendshowList.push(obj)
		}else{
			console.log(name)
			webvue.friendshowList.forEach((item,index)=>{
				if(item.name == name){
					webvue.friendshowList[index].lastmsg = message.data;
					webvue.friendshowList[index].noreadnum = parseInt(webvue.friendshowList[index].noreadnum)+1;
					webvue.friendshowList[index].ishidden = false;
					if(message.from == webvue.current){
						var index = webvue.friendshowList.findIndex((item=>item.name == webvue.current));
						webvue.friendshowList[index].noreadnum = 0;
						webvue.friendshowList[index].ishidden = true;
					}
				}
			})
		}
        pushDialog(getMsgData(msgData,msgtype().TEXT))
		webvue.scrolllistbox()
		if(message.ext.other == 'closevideochatting'){
			webvue.videochatting = false;
		}
		console.log(getDialog())
    },    
    onEmojiMessage: function (message) { },   //收到表情消息
    onPictureMessage: function (message) { //收到图片消息
		console.log('收到图片消息')
		console.log(message)
		var namearr = [];
		var name;
		var sendID;
		if(message.type == 'chat'){
			sendID = message.from;
			name = message.from;
		}else if(message.type == 'groupchat'){
			sendID = message.to;
			webvue.groupList.forEach((item)=>{
				if(item.groupid ==message.to){
					name = item.name
				}
			})
		}
		// var obj = {
		// 	sendID:sendID,
		// 	name:name,
		// 	lastmsg:'',
		// 	time:'2020-06-15',
		// 	noreadnum:1,
		// 	ishidden:true,
		// 	type:message.type
		// }
		webvue.friendshowList.forEach((item,index)=>{
			namearr.push(item.name)
		})
		if(namearr.indexOf(name) == -1){
			var obj = {
				  name:message.from,
				  lastmsg:'[图片]',
				  time:'星期一',
				  noreadnum:1,
				  ishidden:false
			}
			webvue.friendshowList.push(obj)
		}else{
			webvue.friendshowList.forEach((item,index)=>{
				if(item.name == name){
					console.log(name)
					console.log(item.name)
					webvue.friendshowList[index].lastmsg = '[图片]';
					webvue.friendshowList[index].noreadnum = parseInt(webvue.friendshowList[index].noreadnum)+1;
					webvue.friendshowList[index].ishidden = false;
					if(message.from == webvue.current){
						var index = webvue.friendshowList.findIndex((item=>item.name == webvue.current));
						webvue.friendshowList[index].noreadnum = 0;
						webvue.friendshowList[index].ishidden = true;
					}
				}
			})
		}
		// webvue.friendshowList.forEach((item,index)=>{
		// 	namearr.push(item.name)
		// })
		// if(namearr.indexOf(name) == -1){
		// 	webvue.friendshowList.unshift(obj)
		// }else{
		// 	webvue.friendshowList.forEach((item,index)=>{
		// 		if(item.name == name){
		// 			item.ishidden = false;
		// 			item.noreadnum =parseInt(item.noreadnum)+1;
		// 		}
		// 		if(webvue.current != -1){
		// 			if(webvue.friendshowList[webvue.current].name == name){
		// 				item.ishidden = true;
		// 			}
		// 		}
		// 	})
		// }
		webvue.ifallmsgclear()
		let msgData = {
			self:'main',
			type:msgtype().IMAGE,
			value:message.url,
			valuearr:[message.url],
			from:message.from,
			to:message.to
		}
		pushDialog(msgData)
		webvue.scrolllistbox()
	}, 
    onCmdMessage: function (message) { },     //收到命令消息
    onAudioMessage: function (message) { },   //收到音频消息
    onLocationMessage: function (message) { },//收到位置消息
    onFileMessage: function (message) { //收到文件消息
		console.log('收到文件消息')
		console.log(message)
	},    
    onVideoMessage: function (message) {
        var node = document.getElementById('privateVideo');
        var option = {
            url: message.url,
            headers: {
                'Accept': 'audio/mp4'
            },
            onFileDownloadComplete: function (response) {
                var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
                node.src = objectURL;
            },
            onFileDownloadError: function () {
                console.log('File down load error.')
            }
        };
        WebIM.utils.download.call(conn, option);
    },   //收到视频消息
	onCustomMessage: function ( message ) {
		//收到自定义消息
		console.log('>>>自定义消息',message)
		//语音：audio
		var type = message.customExts.type;
		var data = message.customExts.data;
		if(data == 0){
			//共享方停止共享
			webvue.sharing = false;
			webvue.openscreen = false;
		}
	},  
    onPresence: function (message) { //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
        console.log('互动消息',message)
		switch(message.type){
			case 'subscribe':
				//别人申请你为好友
				webvue.isdot = true;
				message.isadd = false; 
				
				pushFriendAskList(message)
				console.log(getFriendAskList())
			break;
			case 'unsubscribed':
				//删除好友
				var mess = '您已跟'+message.from+'解除好友关系'
				webvue.$message(mess);
				webvue.getFriends()
			break;
			case 'subscribed':
				//别人同意你的好友申请
				webvue.friendasklist.forEach((item,index)=>{
					if(item.from == message.from){
						item.isadd = true;
					}
				})
				webvue.$message({
				  message: message.from+'同意你的好友申请啦！',
				  type: 'success'
				});
				webvue.getFriends()
			break;
			case 'direct_joined':
				//直接被拉进群
				var mess = '你已被'+message.owner+'群主拉入群';
				webvue.$message(mess);
				webvue.getGroups()				
			break;
			case 'removedFromGroup':
				//从群组移除
				// var mess = '你已被'+message.owner+'群主踢出群';
				// webvue.$message(mess);
				webvue.getGroups()		
			break;
			case 'deleteGroupChat':
				//群被解散
				var mess = '群已被'+message.owner+'解散';
				webvue.$message(mess);
				webvue.getGroups()		
			break;
			case 'leave':
			  //有人退出群
			  var mes = message.from+'已退出群聊';
			  let msgData1 = {
			  	self:'other',
			  	type:'out',
			  	value:mes,
			  }
			  pushDialog(msgData1)
			 break;
			case 'joinGroupNotifications':
				// 申请入群
				var obj = {
					type:message.type,
					groupid:message.gid,
					from:message.from,
					status:'申请入群：'+message.status.description
				}
				webvue.isdot = true;
				message.isadd = false;
				pushFriendAskList(obj)
				console.log(getFriendAskList())
			break;
			case 'joinPublicGroupSuccess':
				// 对方同意自己的入群申请
				var mes = webvue.name+'已加入群聊';
				let msgData2 = {
					self:'other',
					type:'out',
					value:mes,
				}
				pushDialog(msgData2)
				webvue.getGroups()
			break;
			case 'memberJoinPublicGroupSuccess':
				// 管理员同意入群申请
				var mes = message.from+'已加入群聊';
				let msgData3 = {
					self:'other',
					type:'out',
					value:mes,
				}
				pushDialog(msgData3)
			break;
			//你这几天还通宵不
			case 'leaveGroup':
				// 有人被群主踢出群
				var mes = message.from+'已被群主踢出群聊';
				var msgData4 = {
					self:'other',
					type:'out',
					value:mes,
				}
				pushDialog(msgData4)
				that.showrightside = false;
			break;
			default:
			break;
		  }
		
    },      
    onRoster: function (message) {//处理好友申请
		console.log('处理好友申请',message)
	},         
    onInviteMessage: function (message) { },  //处理群组邀请
    onOnline: function () { },                  //本机网络连接成功
    onOffline: function () { },                 //本机网络掉线
    onError: function (message) { 
		console.log(message)
		if(message.type == 1){
			//账号密码错误
			webvue.$message.error('用户名或密码错误');
		}else if(message.type == 28){
			return
			//重新登录
			window.location.href ='../pages/login_reg.html'
			webvue.$message.error('请重新登录');
		}
	},          //失败回调
    onBlacklistUpdate: function (list) {       //黑名单变动
        // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
        console.log(list);
    },
    onRecallMessage: function (message) { },      //收到撤回消息回调
    onReceivedMessage: function (message) {
        console.log('消息发送到服务器');
    },    //收到消息送达服务器回执
    onDeliveredMessage: function (message) {
        console.log('消息发送到客户端');
    },   //收到消息送达客户端回执
    onReadMessage: function (message) { },        //收到消息已读回执
    onCreateGroup: function (message) { },        //创建群组成功回执（需调用createGroupNew）
    onMutedMessage: function (message) { }        //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
});

// //有人加入会议，其他人调用joinXX等方法，如果加入成功，已经在会议中的人将会收到
// emedia.mgr.onMemberJoined = function (member) {
//     console.log('有人加入会议，其他人调用joinXX等方法，如果加入成功，已经在会议中的人将会收到')
// };
// //有人退出会议
// emedia.mgr.onMemberExited = function (member) {
//     console.log('有人退出会议')
// };
// //有媒体流添加；比如 自己调用了publish方法（stream.located() === true时），或其他人调用了publish方法。
// emedia.mgr.onStreamAdded = function (member, stream) {
// 	console.log('有媒体流添加')
// };
// //有媒体流移除
// emedia.mgr.onStreamRemoved = function (member, stream) {
// 	console.log('有媒体流移除')
// };
// //角色改变
// emedia.mgr.onRoleChanged = function (role) {
// 	console.log('角色改变')
// };
// //会议退出；自己主动退 或 服务端主动关闭；
// emedia.mgr.onConferenceExit = function (reason, failed) {
//     var reason = (reason || 0);
//     switch (reason){
//         case 0:
//             reason = "正常挂断";
//             break;
//         case 1:
//             reason = "没响应";
//             break;
//         case 2:
//             reason = "服务器拒绝";
//             break;
//         case 3:
//             reason = "对方忙";
//             break;
//         case 4:
//             reason = "失败,可能是网络或服务器拒绝";
//             if(failed === -9527){
//                 reason = "失败,网络原因";
//             }
//             if(failed === -500){
//                 reason = "Ticket失效";
//             }
//             if(failed === -502){
//                 reason = "Ticket过期";
//             }
//             if(failed === -504){
//                 reason = "链接已失效";
//             }
//             if(failed === -508){
//                 reason = "会议无效";
//             }
//             if(failed === -510){
//                 reason = "服务端限制";
//             }
//             break;
//         case 5:
//             reason = "不支持";
//             break;
//         case 10:
//             reason = "其他设备登录";
//             break;
//         case 11:
//             reason = "会议关闭";
//             break;
//     }
// 	console.log(reason)
// };
// //管理员变更
// emedia.mger.onAdminChanged = admin => {
// 	console.log(admin)
// } //admin 管理员信息